package org.ztr.aiollama.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ztr.aiollama.entity.vo.MessageVO;
import org.ztr.aiollama.repository.ChatHistoryRepository;

import java.util.List;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/9/20 20:37
 * @Description: 聊天记录控制器
 * @Version: 1.0
 */
@RestController
@RequestMapping("/ai/history")
public class ChatHistoryController {
    private static final Logger logger = LogManager.getLogger(ChatHistoryController.class);

    private final ChatHistoryRepository chatHistoryRepository;

    private final ChatMemory chatMemory;

    public ChatHistoryController(
            ChatHistoryRepository chatHistoryRepository,
            ChatMemory chatMemory
    ) {
        this.chatHistoryRepository = chatHistoryRepository;
        this.chatMemory = chatMemory;
    }

    @GetMapping("/{type}")
    public List<String> getChatIds(@PathVariable("type") String type) {
        return chatHistoryRepository.getChatIds(type);
    }

    @GetMapping("/{type}/{chatId}")
    public List<MessageVO> getChatHistory(
            @PathVariable("type") String type,
            @PathVariable("chatId") String chatId
    ) {
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if(messages == null) {
            return List.of();
        }
        return messages.stream().map(MessageVO::new).toList();
    }
}
